//
//  LXBuyCarView.m
//  灵秀
//
//  Created by 李田 on 17/3/19.
//  Copyright © 2017年 tianyao. All rights reserved.
//

#import "LXBuyCarView.h"
#import "LXFoodDetailModel.h"

@interface LXBuyCarView ()
// 购物车图片按钮
@property (weak, nonatomic) IBOutlet UIButton *buyCarBtn;
// 总价格
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
// 结算按钮
@property (weak, nonatomic) IBOutlet UIButton *payBtn;
// 小红点
@property (weak, nonatomic) IBOutlet UIButton *countBtn;

@end

@implementation LXBuyCarView

#pragma mark - 2.0 赋值
- (void)setBuyArrayList:(NSArray<LXFoodDetailModel *> *)buyArrayList {
    
    _buyArrayList = buyArrayList;
    // 设置按钮的状态
    _buyCarBtn.selected = !(buyArrayList.count == 0);
    _countBtn.hidden = (buyArrayList.count == 0);
    _buyCarBtn.enabled = !(buyArrayList.count == 0);
    
    // 总个数
    __block NSInteger allCount = 0;
    
    // 总价格
    __block CGFloat  allPrice = 0;
    // 差多少钱
    
    [buyArrayList enumerateObjectsUsingBlock:^(LXFoodDetailModel * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        
        // 计算累加的总个数
        allCount += model.buyCount;
        
        // 计算总金额
        allPrice += model.buyCount * model.min_price.floatValue;
    }];
    
    
    
    // 小红点 显示总个数
    [_countBtn setTitle:@(allCount).description forState:UIControlStateNormal];
    
    // 中间显示的总金额
    if(allPrice){
        
        _priceLabel.textColor = [UIColor redColor];
        _priceLabel.text = [NSString stringWithFormat:@"¥%.2f",allPrice];
        
    }else{
        
        _priceLabel.textColor = [UIColor lightGrayColor];
        _priceLabel.text = @"空空如也";
    }
    
    // 结算按钮
    CGFloat minPrice = allPrice - 20;
    
    if (minPrice >= 0) {
        
        _payBtn.backgroundColor = [UIColor orangeColor];
        [_payBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_payBtn setTitle:@"结算" forState:UIControlStateNormal];
    }else{
        
        _payBtn.backgroundColor = [UIColor grayColor];
        [_payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        NSString *minStr = [NSString stringWithFormat:@"还差%.2f",ABS(minPrice)];
        [_payBtn setTitle:minStr forState:UIControlStateNormal];
    }
    
    // 购物车按钮的动画
    _buyCarBtn.transform = CGAffineTransformMakeScale(0.8, 0.8);
    
    [UIView animateWithDuration:.2 delay:0 usingSpringWithDamping:0.3 initialSpringVelocity:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        
        _buyCarBtn.transform = CGAffineTransformIdentity;
    } completion:nil];
}

#pragma mark - 1.0 购物车按钮的点击事件
- (IBAction)buyCarBtnAction:(UIButton *)sender {
    
    if ([_delegate respondsToSelector:@selector(buyCarView:withSelectedArray:)]) {
        
        [_delegate buyCarView:self withSelectedArray:_buyArrayList];
    }
}


@end
